// WiFiManager.cpp
#include "WiFiManager.h"

bool WiFiManager::begin()
{
    WiFiConfig &wifiConfig = config.getWiFiConfig();

    if (strlen(wifiConfig.ssid) > 0)
    {
        if (wifiConfig.isAP)
        {
            return startAP(wifiConfig.ssid, wifiConfig.password);
        }
        else
        {
            return connectToWiFi(wifiConfig.ssid, wifiConfig.password);
        }
    }
    return false;
}

bool WiFiManager::connectToWiFi(const char *ssid, const char *password)
{
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    lastConnectAttempt = millis();
    connected = false; // 明确设置连接状态
    return true;
}

bool WiFiManager::startAP(const char *ssid, const char *password)
{
    WiFi.mode(WIFI_AP);
    if (password && strlen(password) >= 8)
    {
        WiFi.softAP(ssid, password);
    }
    else
    {
        WiFi.softAP(ssid);
    }
    connected = true;
    return true;
}
void WiFiManager::update()
{
    wl_status_t status = WiFi.status();

    if (!connected && status == WL_CONNECTED)
    {
        connected = true;
        DEBUG_PRINTLN("WiFi connected - IP: " + WiFi.localIP().toString());
    }
    else if (connected && status != WL_CONNECTED)
    {
        connected = false;
        DEBUG_PRINTLN("WiFi disconnected");

        // 重连逻辑
        WiFiConfig &wifiConfig = config.getWiFiConfig();
        if (!wifiConfig.isAP && wifiConfig.autoConnect &&
            strlen(wifiConfig.ssid) > 0 &&
            millis() - lastConnectAttempt > 30000)
        {
            DEBUG_PRINTLN("Attempting WiFi reconnection...");
            connectToWiFi(wifiConfig.ssid, wifiConfig.password);
        }
    }
}
void WiFiManager::disconnect()
{
    WiFi.disconnect(true); // true 表示关闭WiFi
    connected = false;
    delay(800); // 等待断开完成
}

String WiFiManager::getStatus()
{
    if (WiFi.getMode() & WIFI_AP)
    {
        return "AP mode - " + String(WiFi.softAPgetStationNum()) + " clients";
    }
    else if (connected)
    {
        return "Connected - IP: " + WiFi.localIP().toString();
    }
    else
    {
        return "Disconnected";
    }
}